package cn.tedu.ivos.vehicle.service.impl;

import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleSaveParam;
import cn.tedu.ivos.vehicle.pojo.entity.Vehicle;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import cn.tedu.ivos.vehicle.service.VehicleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class VehicleServiceImpl implements VehicleService {
    @Autowired
    VehicleMapper vehicleMapper;

    @Override
    public List<VehicleVO> selectVehicle(VehicleQuery vehicleQuery) {
        log.debug("查询车辆业务:{}",vehicleQuery);
        List<VehicleVO> list = vehicleMapper.selectVehicle(vehicleQuery);
        return list;
    }

    @Override
    public void saveVehicle(VehicleSaveParam vehicleSaveParam) {
        log.debug("保存车辆业务:{}",vehicleSaveParam);
        Vehicle vehicle = new Vehicle();
        BeanUtils.copyProperties(vehicleSaveParam,vehicle);
        if(vehicle.getId() == null){//新增
            vehicle.setCreateTime(new Date());
            vehicle.setStatus("1");//新增的车辆状态为空闲
            vehicle.setGeofenceBindStatus("0");//新增的车辆都未绑定围栏
            vehicleMapper.insert(vehicle);
        }else{//更新
            vehicle.setUpdateTime(new Date());
            vehicleMapper.update(vehicle);
        }
    }

    @Override
    public void deleteVehicle(Long id) {
        log.debug("删除车辆业务:{}",id);
        vehicleMapper.deleteVehicle(id);
    }

    @Override
    public void unbindVehicle(Long vehicleId) {
        log.debug("解除车辆绑定业务:{}",vehicleId);
        Vehicle vehicle = new Vehicle();
        //以下都是向vehicle对象中封装update语句的条件
        vehicle.setId(vehicleId);//设置修改哪辆车
        vehicle.setGeofenceBindStatus("0");//设置围栏绑定状态为"未绑定"
        vehicle.setUpdateTime(new Date());
        vehicle.setGeofenceId(null);
        /* 之前写过的更新SQL要求围栏id不为null才会更新围栏id
        * 但此处的业务要求:解绑车辆时,车辆的围栏id要改为null
        * 所以复用不了之前的update,需要再新写一个! */
        vehicleMapper.updateNullValue(vehicle);
    }

    @Override
    public void bindVehicle(Long geofenceId, Long vehicleId) {
        log.debug("绑定车辆业务:{},{}",geofenceId,vehicleId);
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setGeofenceId(geofenceId);
        vehicle.setGeofenceBindStatus("1");//设置当前车辆的围栏绑定状态为"已绑定"
        vehicle.setUpdateTime(new Date());
        vehicleMapper.update(vehicle);
    }
}
